package cn.clq.ymcc.service.impl;

import cn.clq.ymcc.domain.KillActivity;
import cn.clq.ymcc.domain.KillCourse;
import cn.clq.ymcc.mapper.KillActivityMapper;
import cn.clq.ymcc.service.IKillActivityService;
import cn.clq.ymcc.service.IKillCourseService;
import cn.clq.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stone.chen
 * @since 2022-08-04
 */
@Slf4j
@Service
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {

    @Autowired
    private IKillCourseService killCourseService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    /**
     * @description: 发布秒杀活动
     * 1.查询出秒杀活动对应的课程
     * 2.校验时间是否满足，满足条件才发布活动
     * 3.将活动下面的所有课程存储redis
     * 4.redis 中设置每一个秒杀课程对应的库存 -- 信号量
     * 5.结束，修改活动状态
     * @param: activityId
     * @return: cn.clq.ymcc.result.JSONResult
     * @author clqlongbao
     * @date: 2022/8/6 1:36
     */
    @Override
    public void publish(Long activityId) {
        //1.查询出秒杀活动对应的课程
        List<KillCourse> killCourses = selectAllKillCourse(activityId);
        AssertUtil.isNotNull(killCourses,"请先为秒杀活动添加秒杀课程");
        //2.校验时间是否满足，满足条件才发布活动(当前时间在结束时间之前即可上架)
        KillCourse anyKillCourse = killCourses.get(0);
        Date now = new Date();
        boolean before = now.before(anyKillCourse.getEndTime());
        AssertUtil.isTrue(before,"该秒杀活动已经结束，无法发布");
        //3.将活动下面的所有课程存储redis
        killCourses.forEach(killCourse -> {
            //4.在redis中使用信号量为每一个秒杀课程设置对应的库存
            String key = activityId+":"+killCourse.getId();
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            boolean setPermits = semaphore.trySetPermits(killCourse.getKillCount());
            if(setPermits){
                log.info("秒杀课程添加成功，{}",killCourse);
                //为了查询秒杀列表方便，这里我们统一增加大key 的前缀：activity:
                redisTemplate.opsForHash().put("activity:"+activityId,killCourse.getId().toString(),killCourse);
                killCourse.setPublishTime(now);
                killCourse.setPublishStatus(1);
                killCourseService.updateById(killCourse);
            }else{
                log.info("秒杀课程添加失败，{}",killCourse);
            }
        });
        //5.结束，修改活动状态
        KillActivity killActivity = selectById(activityId);
        killActivity.setPublishTime(now);
        killActivity.setPublishStatus(1);
        updateById(killActivity);
    }

    private List<KillCourse> selectAllKillCourse(Long activityId) {
        Wrapper<KillCourse> wrapper = new EntityWrapper<>();
        wrapper.eq("activity_id",activityId);
        return killCourseService.selectList(wrapper);
    }
}
